package com.exchange.service;

import com.exchange.dto.ProductDto;
import com.exchange.entity.Product;
import com.exchange.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    @Autowired
    private ResourceLimitService resourceLimitService;
    
    public Optional<ProductDto> findById(Long id) {
        return productRepository.findById(id)
                .map(ProductDto::fromEntity);
    }
    
    public List<ProductDto> findByMerchantId(Long merchantId) {
        return productRepository.findByMerchantId(merchantId)
                .stream()
                .map(ProductDto::fromEntity)
                .collect(Collectors.toList());
    }
    
    public ProductDto createProduct(Product product, Long merchantId) {
        // Check if merchant has reached product limit (this will also be checked by AOP)
        if (!resourceLimitService.isWithinProductLimit(merchantId, null)) {
            throw new RuntimeException("Merchant has reached the maximum number of products");
        }
        
        product.setMerchantId(merchantId);
        product.setCreatedAt(java.time.LocalDateTime.now());
        product.setUpdatedAt(java.time.LocalDateTime.now());
        Product savedProduct = productRepository.save(product);
        return ProductDto.fromEntity(savedProduct);
    }
    
    public ProductDto updateProduct(Long id, Product productDetails) {
        Optional<Product> existingProduct = productRepository.findById(id);
        if (existingProduct.isPresent()) {
            Product product = existingProduct.get();
            product.setName(productDetails.getName());
            product.setDescription(productDetails.getDescription());
            product.setImageUrl(productDetails.getImageUrl());
            product.setPrice(productDetails.getPrice());
            product.setStockQuantity(productDetails.getStockQuantity());
            product.setCategory(productDetails.getCategory());
            product.setStatus(productDetails.getStatus());
            product.setUpdatedAt(java.time.LocalDateTime.now());
            
            Product updatedProduct = productRepository.save(product);
            return ProductDto.fromEntity(updatedProduct);
        }
        return null;
    }
    
    public boolean deleteProduct(Long id) {
        if (productRepository.existsById(id)) {
            productRepository.deleteById(id);
            return true;
        }
        return false;
    }
    
    public ResourceLimitService.ResourceUsage getResourceUsage(Long merchantId) {
        return resourceLimitService.getUsageForMerchant(merchantId);
    }
}